package com.example.plugin.hook;

import java.lang.reflect.Method;

import android.content.Context;
import android.util.Log;

public class HookedMethodHandler {

	protected Context mContext;
	private Object mFakedResult = null;
	private boolean mUseFakedResult = false;

	public HookedMethodHandler(Context context) {
		this.mContext = context;
	}

	public void setFakedResult(Object fakedResult) {
		this.mFakedResult = fakedResult;
		mUseFakedResult = true;
	}

	public synchronized Object doHook(Object receiver, Method method,
			Object[] args) throws Throwable {
		
		Log.i("bush", String.format("hook %s", method.getName()));
		
		try {
			boolean suc = beforeInvoke(receiver, method, args);
			Object invokeResult = null;
			if (!suc) {
				invokeResult = method.invoke(receiver, args);
			}
			afterInvoke(receiver, method, args, invokeResult);

			if (mUseFakedResult) {
				return mFakedResult;
			} else {
				return invokeResult;
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}

		return null;
	}

	protected boolean beforeInvoke(Object receiver, Method method, Object[] args)
			throws Throwable {
		return false;
	}

	protected void afterInvoke(Object receiver, Method method, Object[] args,
			Object invokeResult) throws Throwable {
	}
}
